﻿using System.Net;
using System.Net.Sockets;
using System.Text;

// 1. 创建服务器监听器
TcpListener listener = new TcpListener(IPAddress.Any, 5000);
List<TcpClient> clients = new(); // 存储所有已连接客户端

listener.Start(); // 启动监听
Console.WriteLine("服务器启动，监听端口 5000...");

// 2. 主线程接收新客户端连接
while (true)
{
    TcpClient client = listener.AcceptTcpClient(); // 阻塞，等待客户端连接
    clients.Add(client); // 保存客户端
    Console.WriteLine("客户端已连接");

    _ = Task.Run(() => HandleClient(client)); // 异步处理客户端通信
}

// 3. 处理某个客户端的消息
void HandleClient(TcpClient client)
{
    using NetworkStream stream = client.GetStream(); // 获取客户端的网络流
    byte[] buffer = new byte[1024]; // 创建缓冲区
    int bytesRead;

    try
    {
        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
        {
            // 读取消息
            string msg = Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine("接收到消息：" + msg);

            // 广播给其他客户端
            BroadcastMessage(msg, client);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("客户端断开：" + ex.Message);
    }
    finally
    {
        // 清理资源
        clients.Remove(client);
        client.Close();
    }
}

// 4. 向所有其他客户端广播消息
void BroadcastMessage(string message, TcpClient sender)
{
    byte[] msgBuffer = Encoding.UTF8.GetBytes(message);

    foreach (var client in clients)
    {
        if (client != sender) // 不回传给发送者
        {
            try
            {
                client.GetStream().Write(msgBuffer, 0, msgBuffer.Length);
            }
            catch
            {
                // 忽略失败的连接
            }
        }
    }
}